import requestApi from '@/util/request';
import { type Device } from '@/types/device';

export async function getDeviceList(): Promise<Array<Device>> {
  const data = await requestApi(`/device/get_device_list`, 'get', {});
  const deviceList: Array<Device> = []
  for (let i = 0; i < data.length; i++) {
    const device: Device = {
      id: data[i].id,
      name: data[i].name,
      ip: data[i].ip,
      port: data[i].port,
      protocol: data[i].protocol,
      isConnected: data[i].is_connected,
    }
    deviceList.push(device);
  }
  return deviceList;
}

export async function addDevice(device: Device): Promise<boolean> {
  return await requestApi(`/device/add_device`, 'post', {
    "device_name": device.name,
    "ip": device.ip,
    "port": device.port,
    "protocol": device.protocol,
  });
}

export async function editDevice(device: Device): Promise<boolean> {
  return await requestApi(`/device/edit_device`, 'post', {
    "device_id": device.id,
    "device_name": device.name,
    "ip": device.ip,
    "port": device.port,
    "protocol": device.protocol,
  });
}

export async function deleteDevice(device_name: string): Promise<boolean> {
  return await requestApi(`/device/delete_device`, 'post', {
    "device_name": device_name,
  });
}

export async function getLatestMessage(device_name: string): Promise<Array<string>> {
  return await requestApi(`/device/get_latest_message`, 'post', {
    "device_name": device_name,
  });
}

// 打开连接 API 函数
export async function openConnection(deviceName: string): Promise<boolean> {
  return await requestApi(`/device/open_connection`, 'post', {
    "device_name": deviceName,
  });
}

// 断开连接 API 函数
export async function closeConnection(deviceName: string): Promise<boolean> {
  return await requestApi(`/device/close_connection`, 'post', {
    "device_name": deviceName,
  });
}